import 'package:flutter/material.dart';
import 'package:dio/dio.dart';
import 'package:flutter_swiper/flutter_swiper.dart';

import 'package:wanandroid_flutter/model/banner_model.dart';
import 'package:wanandroid_flutter/utils/router_push_util.dart';
import 'package:wanandroid_flutter/api/common_service.dart';

class CarouselWidget extends StatefulWidget {
  _CarouselWidgetState createState() => _CarouselWidgetState();
}

class _CarouselWidgetState extends State<CarouselWidget> {
  Dio dio;
  List<BannerData> _bannerList = List();

  @override
  void initState() {
    dio = Dio();
    _bannerList.add(null);
    _getBanner();
    super.initState();
  }

  /// ==============================================

  @override
  Widget build(BuildContext context) {
    return RefreshSageArea(
      child: Swiper(
        itemHeight: 100.0,
        itemBuilder: (BuildContext context, int index) {
          if (_bannerList[index] == null ||
              _bannerList[index].imagePath == null) {
            return Container(
              color: Colors.grey[100],
            );
          } else {
            return _carouselItem(context, index);
          }
        },
        itemCount: _bannerList.length,
        autoplay: true,
        pagination: SwiperPagination(),
      ),
    );
  }

  Widget _carouselItem(BuildContext context, int index) {
    return InkWell(
      onTap: () {
        RouterPush.toWebview(
            context, _bannerList[index].title, _bannerList[index].url);
      },
      child: Container(
        child: Image.network(
          _bannerList[index].imagePath,
          fit: BoxFit.fitWidth,
        ),
      ),
    );
  }

  Future<Null> _getBanner() async {
    CommonService().getBanner((BannerModel _bean) {
      if (_bean.data.length > 0) {
        setState(() {
          _bannerList = _bean.data;
        });
      }
    });
  }
}

class RefreshSageArea extends StatelessWidget {
  final Widget child;

  RefreshSageArea({Key key, @required this.child}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return NotificationListener(
      onNotification: (ScrollNotification notification) => true,
      child: this.child,
    );
  }
}
